use([
    "public/javascripts/widget/myInput/myInput.js",
    "public/javascripts/service/ordersService.js",
    "public/javascripts/widget/select/select.js",
    "public/common/classNames.js",
    "public/javascripts/widget/dialog/dialog.js",
    "public/javascripts/widget/prompt/prompt.js",
    "public/javascripts/widget/slider/slider.js",
    "public/javascripts/widget/picPreview/picPreview.js",
    "public/javascripts/orders/product.js",
    "public/javascripts/orders/goods.js",
    "public/javascripts/orders/address.js",
    "public/javascripts/orders/cost.js",
    "public/javascripts/orders/annex.js",
    "public/javascripts/orders/message.js",
    "public/javascripts/orders/status.js",
    "public/javascripts/orders/suborder.js",
    'public/javascripts/orders/logistics.js'
], function (MyInputComponent, ordersService, selectFactory, classNames, DialogComponent, PromptComponent, SliderComponent, picPreview,
             ProductComponent, GoodsComponent, AddressComponent, CostComponent, AnnexComponent, MessageComponent, StatusComponent, SuborderComponent,
             LogisticsComponent) {
    var cx = classNames;
    var PageComponent = React.createClass({
        componentDidMount: function () {

            $(".u-expend").click(function () {
                if ($(this).hasClass('closed')) {
                    $('.more-msg-detail').show();
                    $(this).removeClass('closed');
                } else {
                    $('.more-msg-detail').hide();
                    $(this).addClass('closed');
                }
            });

        },
        receiveMsg: function (data) {

        },
        getInitialState: function () {
            return this.props ? this.props : {};
        },
        saveCallback: function (res, type) {    //保存订单成功后的回调
            var _this = this;
            if (res.errorCode == 0) {
                try {
                    if (_this.props.data.info && _this.props.data.info.from == 'product') {
                        window.history.pushState({}, '', '/product_list');
                    } else {
                        window.history.pushState({}, '', '/order_manage');
                    }
                } catch (e) {
                }

                PromptComponent.init({'type': 'success', 'msg': res.msg}).show();

                //展示运单号
                _this.state.data.newOid = res.data[0];

                if (res.data[1]) {
                    setTimeout(function () {
                        PromptComponent.init({'type': 'warning', 'msg': '地址保存失败!'}).show();
                    }, 3000);
                }

                _this.state.data.orderSuccess = true;
                _this.setState();
                $(document).scrollTop(0);
            } else {
                PromptComponent.init({'type': 'warning', 'msg': res.msg}).show();
            }
        },
        getProductData: function (done) {
            eventFlux.call('orders_product_Event', 'getData', function (data) {
                if (!data) {
                    done(null, false);
                } else {
                    done(null, data);
                }
            });
        },
        getGoodsData: function (done) {
            eventFlux.call('orders_goods_Event', 'getData', function (data) {
                if (!data) {
                    done(null, false);
                } else {
                    done(null, data);
                }
            });
        },
        getAddressData: function (done) {
            eventFlux.call('orders_address_Event', 'getData', function (data) {
                if (!data) {
                    done(null, false);
                } else {
                    done(null, data);
                }
            });
        },
        getAnnexData: function (done) {
            eventFlux.call('orders_annex_Event', 'getData', function (data) {
                if (!data) {
                    done(null, false);
                } else {
                    done(null, data);
                }
            });
        },
        getMessageData: function (done) {
            eventFlux.call('orders_message_Event', 'getData', function (data) {
                if (!data) {
                    done(null, false);
                } else {
                    done(null, data);
                }
            });
        },
        submitOrder: function (type) {    //保存订单
            var _this = this;
            var uploadSuccessful = window.localStorage.getItem("uploadSuccessful");

            _this.state.data.submitType = type;    //保存类型

            async.parallel({
                'product': _this.getProductData,    //产品订单基本信息
                'goods': _this.getGoodsData,        //物品信息
                'address': _this.getAddressData,    //地址信息
                'annex': _this.getAnnexData,        //附件信息
                'message': _this.getMessageData,    //留言信息
            }, function (err, result) {
                if (uploadSuccessful === "false") {
                    return
                }
                if (result.address === false || result.goods === false || result.product === false) {
                    //跳转到错误位置。
                    setTimeout(function () {
                        var errEle = $.merge($('.error-msg'), $('.required'));
                        scrollToErrorView($(document));
                    }, 500);
                } else {
                    _this.submitData(result, type);
                }
            });
        },
        submitData: function (retData, type) {
            var _this = this;

            var oid = _this.state.data.info && _this.state.data.info.oid;

            //组织提交数据
            var data = {};
            data = $.extend({}, retData.product);
            data.cusUserId = cookie.get('userId');
            data.fileDtos = retData.annex;    //附件
            data.orderCargoDtos = retData.goods;    //物品
            data.customerNote = retData.message || '';   //留言
            data.orderStatus = type;    //保存草稿、提交订单
            data.fetchAddress = retData.address.fetchAddress;
            if (data.fetchAddress && data.fetchAddress.transportType) {
                data.fetchAddress.transportType == 11;
            }
            data.fetchName = retData.address.fetchName;
            data.fetchPhone = retData.address.fetchPhone;
            data.fetchTelephone = retData.address.fetchTelephone;
            data.fetchPostcode = retData.address.fetchPostcode;
            data.fromAddress = retData.address.fromAddress;
            data.fromName = retData.address.fromName;
            data.fromPhone = retData.address.fromPhone;
            data.fromTelephone = retData.address.fromTelephone;
            data.fromPostcode = retData.address.fromPostcode;
            data.toAddress = retData.address.toAddress;
            data.toName = retData.address.toName;
            data.toPhone = retData.address.toPhone;
            data.toTelephone = retData.address.toTelephone;
            data.toPostcode = retData.address.toPostcode;

            var config = {
                'urlParams': data
            };
            if (oid) {    //编辑订单
                config.urlParams.orderNo = oid;
                config.seatParams = {
                    'orderNo': oid
                };
                ordersService.editOrder(config, function (res) {
                    _this.saveCallback(res);
                });
            } else {    //新增订单
                if (type === 'DRAFT') {
                    ordersService.addOrder(config, function (res) {
                        _this.saveCallback(res);
                    });
                } else {
                    DialogComponent.init({
                        'type': 'confirm', 'msg': '确认提交订单？', "success": function () {
                            ordersService.addOrder(config, function (res) {
                                if (res.errorCode === 0) {
                                    _this.state.data.info.oid = res.data[0];
                                }

                                _this.saveCallback(res);
                            });
                        }
                    }).show();
                }
            }
        },
        submitHighVolumeOrderData:function(retData){
            var _this = this;
            var data = {};
            data = $.extend({}, retData.product);
            data.cusUserId = cookie.get('userId');

            data.fileDtos = retData.annex;    //附件
            data.cargos = retData.goods;    //物品
            data.customerNote = retData.message || '';   //留言
            //data.orderStatus = type;    //保存草稿、提交订单
            data.fetchAddress = retData.address.fetchAddress;
            if (data.fetchAddress && data.fetchAddress.transportType) {
                data.fetchAddress.transportType == 11;
            }
            data.fetchName = retData.address.fetchName;
            data.fetchPhone = retData.address.fetchPhone;
            data.fetchTelephone = retData.address.fetchTelephone;
            data.fetchPostcode = retData.address.fetchPostcode;
            data.fromAddress = retData.address.fromAddress;
            data.fromName = retData.address.fromName;
            data.fromPhone = retData.address.fromPhone;
            data.fromTelephone = retData.address.fromTelephone;
            data.fromPostcode = retData.address.fromPostcode;
            data.toAddress = retData.address.toAddress;
            data.toName = retData.address.toName;
            data.toPhone = retData.address.toPhone;
            data.toTelephone = retData.address.toTelephone;
            data.toPostcode = retData.address.toPostcode;

            var config = {
                'urlParams': data,
                'seatParams':{
                    "id":this.state.data.info.highVolumeOrderId
                }
            };

            ordersService.modifyHighVolumeOrder(config, function (res) {

                var info  = _this.state.data.info;
                if (res.errorCode == 0) {

                    setTimeout(function () {
                        window.location.href = '/highVolumeOrders?'+ '&batchNumber=' + info.batchNumber +'&q='+info.q +'&verifiedStatus='+info.verifiedStatus+'&pageSize=' + info.pageSize +'&pageIndex=' + info.pageIndex +'&relate=product_list'

                    },500)

                    PromptComponent.init({'type': 'success', 'msg': res.msg}).show();

                } else {
                    PromptComponent.init({'type': 'warning', 'msg': res.msg}).show();
                }
            });

        },
        saveHighVolumeOrder:function () { // 这里还是重新写，不要影响原来的流程
            var _this = this;
            var uploadSuccessful = window.localStorage.getItem("uploadSuccessful");

            async.parallel({
                'product': _this.getProductData,    //产品订单基本信息
                'goods': _this.getGoodsData,        //物品信息
                'address': _this.getAddressData,    //地址信息
                'annex': _this.getAnnexData,        //附件信息
                'message': _this.getMessageData,    //留言信息
            }, function (err, result) {
                if (uploadSuccessful === "false") {
                    return
                }
                if (result.address === false || result.goods === false || result.product === false) {
                    //跳转到错误位置。
                    setTimeout(function () {
                        var errEle = $.merge($('.error-msg'), $('.required'));
                        scrollToErrorView($(document));
                    }, 500);
                } else {
                    _this.submitHighVolumeOrderData(result);
                }
            });

        },
        costCount: function () {    //预估费用
            var _this = this;

            var oid = _this.state.data.info && _this.state.data.info.oid;

            async.parallel({
                'product': _this.getProductData,    //产品订单基本信息
                'goods': _this.getGoodsData,        //物品信息
                'address': _this.getAddressData,    //地址信息
                'annex': _this.getAnnexData,        //附件信息
                'message': _this.getMessageData,    //留言信息
            }, function (err, result) {
                if (result.address === false || result.product === false) {
                    //跳转到错误位置。
                    setTimeout(function () {
                        var errEle = $.merge($('.error-msg'), $('.required'));
                        scrollToErrorView($(document));
                    }, 500);
                } else {
                    //组织提交数据
                    var data = {
                        cargoTypeCode: result.product.cargoTypeCode,
                        customerId: cookie.get('userId'),
                        productUid: result.product.productUid,
                        weight: result.product.cusWeight,
                        unitCode: result.product.cusWeightUnit,    //重量单位
                    };

                    data.optionServiceTypes = [];

                    if(result.product && result.product.orderAdditionalDtos){
                        result.product.orderAdditionalDtos.forEach(function(item, index){
                            data.optionServiceTypes.push(item.serviceTypeCode);
                        })
                    }

                    var announcePrice = 0;
                    if ((typeof result.goods == 'object') && result.goods.length) {
                        result.goods.forEach(function (item, index) {
                            announcePrice += (item.goodsPrice * item.goodsNumber);
                        });
                    }
                    data.announcePrice = announcePrice; //声明价值，没有则为0

                    if (result.address.productGroupRootId != 11) {
                        data.startPort = result.address.fromAddress.transportId;
                        data.endPort = result.address.toAddress.transportId;
                    } else {
                        data.fromCountry = result.address.fromAddress.countryCode;
                        data.fromPostcode = result.address.fromAddress.postcode;
                        if (result.address.fromAddress.countryCode == 'CN') {
                            data.fromProvince = result.address.fromAddress.provinceId;
                            data.fromCity = result.address.fromAddress.cityId;
                            data.fromArea = result.address.fromAddress.districtId;
                            data.fromStreet = result.address.fromAddress.streetId;
                        } else {
                            data.fromCity = result.address.fromAddress.cityId;
                        }

                        data.toCountry = result.address.toAddress.countryCode;
                        data.toPostcode = result.address.toAddress.postcode;
                        if (result.address.toAddress.countryCode === 'CN') {
                            data.toProvince = result.address.toAddress.provinceId;
                            data.toCity = result.address.toAddress.cityId;
                            data.toArea = result.address.toAddress.districtId;
                            data.toStreet = result.address.toAddress.streetId;
                        } else {
                            data.toCity = result.address.toAddress.cityId;
                        }
                    }

                    if (result.address.isHaveReceive) {    //揽收服务
                        data.fetchCountry = result.address.fetchAddress.countryCode;
                        data.fetchPostcode = result.address.fetchAddress.postcode;
                        if (result.address.fetchAddress.countryCode === 'CN') {
                            data.fetchProvince = result.address.fetchAddress.provinceId;
                            data.fetchCity = result.address.fetchAddress.cityId;
                            data.fetchArea = result.address.fetchAddress.districtId;
                            data.fetchStreet = result.address.fetchAddress.streetId;
                        } else {
                            data.fetchCity = result.address.fetchAddress.cityId;
                        }
                    }

                    ordersService.saleProduct(data, function (res) {
                        if (res.errorCode == 0) {
                            _this.setState({'amount':res.data.amount, 'currency':'('+ res.data.currency +')'})
                        } else {
                            PromptComponent.init({'type': 'warning', 'msg': '费用详情请联系客服'}).show();
                        }
                    });
                }
            });
        },
        render: function () {
            var data = this.state.data;
            var info = this.state.data.info;

            console.log(data, info);
            return ~init;
        }
    });

    if (typeof ReactDOM != "undefined") {
        ReactDOM.render(<PageComponent data={storage}/>, document.getElementById('container'));
    }
    module.exports = PageComponent;
});